package com.sara.loader;
//
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.protocol.HTTP;

import android.util.Log;

import com.android.json.stream.JsonObjectReader;
import com.android.json.stream.JsonReader;
import com.gmcc.tripleplay.app.Constants;
import com.gmcc.tripleplay.entity.ResultCode;
import com.sara.util.Utils;

public class JsonResponseParser<T extends ResultCode> extends ResponseParser {

	private static final String TAG = "JSON_RESULT";

	private Class<T> clazz;

	public JsonResponseParser(Class<T> clazz, ResponseListener listener) {
		super(listener);
		this.clazz = clazz;
	}

	@Override
	public void doParse(String url, HttpResponse httpresp, InputStream is,
			String postData) {
		super.doParse(url, httpresp, is, postData);
		if (netResult) {
			InputStream inputStream = is;
			try {
				if (Constants.DEBUG) {
					String result = Utils.getInputStreamText(is, HTTP.UTF_8);
					Log.d(TAG, result);
					inputStream = new ByteArrayInputStream(result.getBytes());
				}
				T data = clazz.newInstance();
				JsonReader jsonReader = new JsonReader(new InputStreamReader(
						inputStream, HTTP.UTF_8));
				JsonObjectReader joReader = new JsonObjectReader(jsonReader);
				joReader.readObject(data);

				Response response = new Response();
				response.setCode(data.code);
				response.setResponseObject(data);
				response(response);
			} catch (Exception e) {
				e.printStackTrace();
				Response response = createFailureResponse("500");
				response(response);
			} finally {
				if (inputStream != null) {
					try {
						inputStream.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}
